package com.fwx.chatroom.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/*通过这个类记录用户在线状态*/
@Component
public class OnlineUserManage {
    //此处这个哈希表是线程安全的
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();
    //用户上线，给hash表插入语句
    public void online(int userId, WebSocketSession session) {
        if(sessions.get(userId) != null) {
            //用户已经登录，登录失败
            System.out.println("{" + userId + "}" + "已经登录了！");
            return;
        }
        sessions.put(userId,session);
        System.out.println("{" + userId + "}" + "上线！");
    }
    //用户下线，针对hash表进行删除元素
    public void offerline(int userId,WebSocketSession session) {
        WebSocketSession existSession = sessions.get(userId);
        if (existSession == session) {
            //同一个session，下线操作
            sessions.remove(userId);
            System.out.println("{" + userId + "}" + "下线！");
        }
    }
    //根据用户id获取到WebSession
    public WebSocketSession getSession(int userId) {
        return sessions.get(userId);
    }
}
